/*判断手机端类型*/
function loader_getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;
    if (/windows phone/i.test(userAgent)) {
        return "Windows Phone";
    }
    if (/android/i.test(userAgent)) {
        return "android";
    }
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "ios";
    }
    return "unknown";
}
//url参数拆分
function loader_analysisParam(paras) {
	var url = location.href;
	console.log("url is:" + url);
	var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
	console.log("paraString is:" + paraString);
	var paraObj = {};
  var i,j;
	for (i = 0; j = paraString[i]; i++) {
		paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
	}
	var returnValue = paraObj[paras.toLowerCase()];
	if ( typeof (returnValue) === "undefined") {
		return null;
	} else {
		return returnValue;
	}
}

$(document).on('ready', function() {
  var L=window.navigator.userAgent;
  //比较版本，决定是否从远程取得
  var needUpdate = false;
  var versionRemote = $("#progressBarArea").attr("version");
  var versionLocal = localStorage.getItem("callcloud_version");
  if(!versionLocal){
    versionLocal = 0;
  }
  console.log("versionLocal:" + versionLocal + " and versionRemote:" + versionRemote);
  if(versionLocal<versionRemote){
    needUpdate = true;
  }
  var getScriptKey = function(url){
    var filePart = url.substring(url.lastIndexOf('/')+1);
    var key = "scriptKey_" + filePart;
    key = key.replace(".","_");
    console.log("key is:" + key);
    return key;
  };
  var encodeSrc = function(srcData){
    // var encData = window.btoa(unescape(encodeURIComponent(srcData)));
    // console.log("encData len:" + encData.length);
    // var compressed = LZString.compress(srcData);
    // console.log("compressed len:" + compressed.length);
    return srcData;
  };
  var decodeSrc = function(targetData){
    console.log("targetData len is:" + targetData.length);
    var deCompress = window.pako.ungzip(targetData);
    // var deCompress = gunzip.decompress();
    // var deCompress = LZString.decompress(targetData);
    console.log("deCompress len:" + deCompress.length);
    var binaryconverter = new TextDecoder('utf-8');
    var decodedString = binaryconverter.decode(deCompress);//Uint8ToString(deCompress);
    console.log("decodedString len:" + decodedString.length);
    return decodedString;
  };
  //进度条变化
  var loadProgress = function(evt){
    if (evt.lengthComputable) {
      var percent = evt.loaded / evt.total * 100;
      var progressBarWidth = percent/100 * $("#progressBar").width();
      console.log("progressBarWidth:" + progressBarWidth);
    	$("#progressBar").find('div').width(progressBarWidth).html(percent + "%&nbsp;");
    } else {
      console.log("unable compute length",evt);
    }
  };
  //定义加载脚本
  var load_loadScript = function(type,data,callback,waitCall){
    var headElement = document.getElementsByTagName("head")[0];
    var newScriptElement,newStyleElement;
    if(type==="script"){
      newScriptElement  = document.createElement("script");
      newScriptElement.type = "text/javascript";
      newScriptElement.text = data;
      if(!waitCall){
        headElement.appendChild(newScriptElement);
        callback(data);
        return;
      }
      //延迟加载，直到条件满足
      var wait = function(){
        if (waitCall()) {
          headElement.appendChild(newScriptElement);
          callback();
        } else {
          setTimeout( wait, 500 );
        }
      };
      wait();
    }else{
      console.log("load_loadScript ")
      if(!waitCall){
        $("head").append("<style>" + data + "</style>");
        callback(data);
        return;
      }
      //延迟加载，直到条件满足
      var waitCss = function(){
        if (waitCall()) {
          $("head").append("<style>" + data + "</style>");
          callback();
        } else {
          setTimeout( waitCss, 500 );
        }
      };
      waitCss();
    }
  };
  //定义获取脚本
  var load_queryScript = function (url, type,callback,loadProgressCall,waitCall,failCallback) {
    var key = getScriptKey(url);
    var queryBack = function(backdata){
      if(callback){
        load_loadScript(type,backdata,callback,waitCall);
      }else{
        load_loadScript(type,backdata);
      }
    };
    //如果不需要更新，从本地取得脚本
    if(!needUpdate){
      var encData = localStorage.getItem(key);
      //字符串转为压缩数据的数组
      var data = StringView.base64ToBytes(encData);
      console.log("data len:" + data.length);
      var decData = decodeSrc(data);
      queryBack(decData);
      return;
    }
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.addEventListener("progress", loadProgressCall, false);
    xmlHttp.onload = function(e){
      console.log("this.response len:" + this.response.length);
      var uInt8Array = new Uint8Array(this.response);
      console.log("arrayBuffer len:" + uInt8Array.length);
      console.log("query ok:" + url);
      //脚本的压缩数据转换为字符串，并存储到本地
      var encData = StringView.bytesToBase64(uInt8Array);
      localStorage.setItem(key,encData);
      //解压及处理
      var decData = decodeSrc(uInt8Array);
      queryBack(decData);
    };
    xmlHttp.open("get", url, true);
    xmlHttp.responseType = "arraybuffer";
    xmlHttp.send();
  };
  //加载css
  load_queryScript("assets/styles/app.css","css", function(){
    console.log("app css loaded");
    $("#progressBar").attr("appCssLoaded","yes");
  },null,function(){
    //通过标志控制是否加载,保证先加载verdor css
    console.log("vendorCssLoaded is:" + $("#progressBar").attr("vendorCssLoaded"));
    return $("#progressBar").attr("vendorCssLoaded");
  });
  load_queryScript("assets/vendor.css","css",function(){
    console.log("vendor.css loaded");
    //设置加载完毕标志
    $("#progressBar").attr("vendorCssLoaded","yes");
  });
  //如果是客户端，加载cordova库
  var isCordova = loader_analysisParam("isCordova");
  if(isCordova){
    var osType = loader_getMobileOperatingSystem();
    console.log("need cordova");
    load_queryScript("./cordova/" + osType + "/cordova.js","script",function(){
      console.log("cordova.js load ok");
    });
  }
  load_queryScript("assets/callcloud.js", "script", function(){
    console.log("callcloud loaded");
    var progress = $("#progressBarArea");
    progress.hide();
    //设置版本号
    localStorage.setItem("callcloud_version",versionRemote);
  },null,function(){
    //通过标志控制是否加载
    console.log("vendorLoaded is:" + $("#progressBar").attr("vendorLoaded"));
    var vf = $("#progressBar").attr("vendorLoaded");
    var vsf = $("#progressBar").attr("vendorCssLoaded");
    var asf = $("#progressBar").attr("appCssLoaded");
    var flag = true;
    if(!vf || !vsf ||!asf){
      flag = false;
    }
    console.log("vf:" + vf + " and vsf:" + vsf + " and asf:" + asf + " and flag:"+ flag);
    return flag;
  });
  load_queryScript("assets/vendor.js", "script",function(){
    console.log("vendor loaded");
    //设置加载完毕标志
    $("#progressBar").attr("vendorLoaded","yes");
  },function(e){
    loadProgress(e);
  });
});
